// collaboratingPersonnel.js
const { runAsync, allAsync, getAsync, retryOperation, log } = require('./dbConfig');

/**
 * 新增合作人员
 * @param {Object} req - 请求对象，包含合作人员信息
 * @param {Object} res - 响应对象
 */
const addCollaboratingPersonnel = async (req, res) => {
  const { cooperation_name, nickname, cooperation_sex, partner_company_id, partner_company_name, cooperation_phone, cooperation_wx_num, cooperation_id_num, remarks, individual_img, create_user } = req.body;
  if (!cooperation_name || !cooperation_phone) {
    return res.status(500).json({ success: false, msg: '姓名和手机号为必填项', code: '1', data: [] });
  }

  try {
    // // 检查手机号是否重复
    // const existingUser = await getAsync('SELECT id FROM sk_collaborating_personnel WHERE cooperation_phone = ? AND del_flag = \'0\'', [cooperation_phone]);
    // if (existingUser) {
    //   return res.status(400).json({ success: false, msg: '该手机号已存在请修改后重试', code: '1', data: [] });
    // }

    await retryOperation(() =>
      runAsync(
        `INSERT INTO sk_collaborating_personnel (cooperation_name, nickname, cooperation_sex, partner_company_id, partner_company_name, cooperation_phone, cooperation_wx_num, cooperation_id_num, remarks, individual_img, create_user) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [cooperation_name, nickname, cooperation_sex, partner_company_id, partner_company_name, cooperation_phone, cooperation_wx_num, cooperation_id_num, remarks, individual_img, create_user]
      )
    );
    const result = await getAsync(`SELECT last_insert_rowid() as id`);
    const lastID = result.id;
    log(`Inserted ID: ${lastID}`);
    res.json({ success: true, msg: '新增成功', code: '0', data: [lastID] });
  } catch (err) {
    log(`新增合作人员失败: ${err.message}`);
    res.status(500).json({ success: false, msg: '新增合作人员信息失败，请稍后再试', code: '1', data: [] });
  }
};

/**
 * 修改合作人员信息
 * @param {Object} req - 请求对象，包含更新信息和 ID
 * @param {Object} res - 响应对象
 */
const updateCollaboratingPersonnel = async (req, res) => {
  const { id, cooperation_name, nickname, cooperation_sex, partner_company_id, partner_company_name, cooperation_phone, cooperation_wx_num, cooperation_id_num, remarks, individual_img, update_user } = req.body;

  try {
    // // 检查手机号是否重复（排除自己）
    // const existingUser = await getAsync('SELECT id FROM sk_collaborating_personnel WHERE cooperation_phone = ? AND del_flag = \'0\' AND id != ?', [cooperation_phone, id]);
    // if (existingUser) {
    //   return res.status(400).json({ success: false, msg: '该手机号已存在请修改后重试', code: '1', data: [] });
    // }

    await retryOperation(() =>
      runAsync(
        `UPDATE sk_collaborating_personnel SET cooperation_name = ?, nickname = ?, cooperation_sex = ?, partner_company_id = ?, partner_company_name = ?, cooperation_phone = ?, cooperation_wx_num = ?, cooperation_id_num = ?, remarks = ?, individual_img = ?, update_user = ?, update_time = CURRENT_TIMESTAMP WHERE id = ? AND del_flag = '0'`,
        [cooperation_name, nickname, cooperation_sex, partner_company_id, partner_company_name, cooperation_phone, cooperation_wx_num, cooperation_id_num, remarks, individual_img, update_user, id]
      )
    );
    res.json({ success: true, msg: '修改成功', code: '0', data: [] });
  } catch (err) {
    log(`修改合作人员失败: ${err.message}`);
    res.status(500).json({ success: false, msg: '修改合作人员信息失败，请稍后再试', code: '1', data: [] });
  }
};

/**
 * 删除合作人员（逻辑删除）
 * @param {Object} req - 请求对象，包含 ID
 * @param {Object} res - 响应对象
 */
const deleteCollaboratingPersonnel = async (req, res) => {
  const { id } = req.params;

  try {
    await retryOperation(() =>
      runAsync(`UPDATE sk_collaborating_personnel SET del_flag = '1' WHERE id = ?`, [id])
    );
    res.json({ success: true, msg: '删除成功', code: '0', data: [] });
  } catch (err) {
    log(`删除合作人员失败: ${err.message}`);
    res.status(500).json({ success: false, msg: '删除合作人员信息失败，请稍后再试', code: '1', data: [] });
  }
};

/**
 * 查询合作人员列表（带搜索条件和分页）
 * @param {Object} req - 请求对象，包含搜索条件和分页参数
 * @param {Object} res - 响应对象
 */
const getPageCollaboratingPersonnelList = async (req, res) => {
  const { nickname, cooperation_name, cooperation_phone, partner_company_id, cooperation_id_num, page, size } = req.query;

  const pageNum = parseInt(page) || 1; // 默认第 1 页
  const pageSize = parseInt(size) || 10; // 默认每页 10 条

  let query = 'SELECT * FROM sk_collaborating_personnel WHERE del_flag = \'0\'';
  let countQuery = 'SELECT COUNT(*) as total FROM sk_collaborating_personnel WHERE del_flag = \'0\'';
  const params = [];
  const countParams = [];

  if (nickname) {
    query += ' AND nickname LIKE ?';
    countQuery += ' AND nickname LIKE ?';
    params.push(`%${nickname}%`);
    countParams.push(`%${nickname}%`);
  }

  if (cooperation_name) {
    query += ' AND cooperation_name LIKE ?';
    countQuery += ' AND cooperation_name LIKE ?';
    params.push(`%${cooperation_name}%`);
    countParams.push(`%${cooperation_name}%`);
  }

  if (cooperation_phone) {
    query += ' AND cooperation_phone LIKE ?';
    countQuery += ' AND cooperation_phone LIKE ?';
    params.push(`%${cooperation_phone}%`);
    countParams.push(`%${cooperation_phone}%`);
  }

  if (partner_company_id) {
    query += ' AND partner_company_id = ?';
    countQuery += ' AND partner_company_id = ?';
    params.push(partner_company_id);
    countParams.push(partner_company_id);
  }

  if (cooperation_id_num) {
    query += ' AND cooperation_id_num = ?';
    countQuery += ' AND cooperation_id_num = ?';
    params.push(cooperation_id_num);
    countParams.push(cooperation_id_num);
  }

  query += ' ORDER BY id DESC LIMIT ? OFFSET ?';
  params.push(pageSize, (pageNum - 1) * pageSize);

  try {
    const rows = await allAsync(query, params);
    const countRow = await getAsync(countQuery, countParams);
    res.json({ data: rows, code: '0', success: true, msg: '获取列表成功', total: countRow.total });
  } catch (err) {
    log(`Get collaborating personnel list error: ${err.message}`);
    res.status(500).json({ error: err.message });
  }
};

/**
 * 查询合作人员列表（带搜索条件不分页）
 * @param {Object} req - 请求对象，包含搜索条件
 * @param {Object} res - 响应对象
 */
const getCollaboratingPersonnelList = async (req, res) => {
  const { nickname, cooperation_name, cooperation_phone, partner_company_id, cooperation_id_num } = req.query;
  let query = 'SELECT * FROM sk_collaborating_personnel WHERE del_flag = \'0\'';
  let countQuery = 'SELECT COUNT(*) as total FROM sk_collaborating_personnel WHERE del_flag = \'0\'';
  const params = [];
  const countParams = [];

  if (nickname) {
    query += ' AND nickname LIKE ?';
    countQuery += ' AND nickname LIKE ?';
    params.push(`%${nickname}%`);
    countParams.push(`%${nickname}%`);
  }

  if (cooperation_name) {
    query += ' AND cooperation_name LIKE ?';
    countQuery += ' AND cooperation_name LIKE ?';
    params.push(`%${cooperation_name}%`);
    countParams.push(`%${cooperation_name}%`);
  }

  if (cooperation_phone) {
    query += ' AND cooperation_phone LIKE ?';
    countQuery += ' AND cooperation_phone LIKE ?';
    params.push(`%${cooperation_phone}%`);
    countParams.push(`%${cooperation_phone}%`);
  }

  if (partner_company_id) {
    query += ' AND partner_company_id = ?';
    countQuery += ' AND partner_company_id = ?';
    params.push(partner_company_id);
    countParams.push(partner_company_id);
  }

  if (cooperation_id_num) {
    query += ' AND cooperation_id_num = ?';
    countQuery += ' AND cooperation_id_num = ?';
    params.push(cooperation_id_num);
    countParams.push(cooperation_id_num);
  }

  query += ' ORDER BY id DESC';

  try {
    const rows = await allAsync(query, params);
    const countRow = await getAsync(countQuery, countParams);
    res.json({ data: rows, code: '0', success: true, msg: '获取列表成功', total: countRow.total });
  } catch (err) {
    log(`获取合作人员信息列表失败: ${err.message}`);
    res.status(500).json({ success: false, msg: '获取合作人员列表失败，请刷新重试', code: '1', data: [] });
  }
};

/**
 * 查询合作人员详情
 * @param {Object} req - 请求对象，包含 ID
 * @param {Object} res - 响应对象
 */
const queryCollaboratingPersonnelDetail = async (req, res) => {
  const { id } = req.params;

  try {
    const row = await getAsync('SELECT * FROM sk_collaborating_personnel WHERE id = ? AND del_flag = \'0\'', [id]);
    if (!row) {
      return res.status(500).json({ success: false, msg: '未查询到合作人员信息', code: '1', data: [] });
    }
    res.json({ data: row, code: '0', success: true, msg: '查询详情成功' });
  } catch (err) {
    log(`Get collaborating personnel detail error: ${err.message}`);
    res.status(500).json({ error: err.message });
  }
};

// 模块导出
module.exports = { addCollaboratingPersonnel, updateCollaboratingPersonnel, deleteCollaboratingPersonnel, getPageCollaboratingPersonnelList, getCollaboratingPersonnelList, queryCollaboratingPersonnelDetail };